package com.come4loves.game.module.actor.service.impl;

import io.netty.channel.ChannelHandlerContext;

import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.come4loves.core.comunicate.protocol.Response;
import com.come4loves.core.result.TResult;
import com.come4loves.core.thread.NamedThreadFactory;
import com.come4loves.game.constent.GameStatusCodeConstant;
import com.come4loves.game.module.actor.helper.UserPushHelper;
import com.come4loves.game.module.actor.platform.PlatformInvoke;
import com.come4loves.game.module.actor.platform.PlatformLoginResult;
import com.come4loves.game.module.actor.service.ActorService;
import com.come4loves.game.module.actor.service.UserSerivce;
import com.come4loves.game.server.session.PlayerContext;

/**
 * 用户相关的接口
 * @author ludd
 *
 */
@Component
public class UserServiceImpl implements UserSerivce {
	
	private static int POOL_SIZE = 2;
	private static int MAX_POOL_SIZE = 10;
	private static int KEEP_ALIVE_TIME = 900; //ms

	private ThreadPoolExecutor executor ;
	
	@Autowired
	private PlatformInvoke platformInvoke;
	
	@Autowired
	private ActorService actorService;
	
	@Autowired
	protected PlayerContext playerContext;
	
	@Autowired
	@Qualifier("game.server.id")
	private int serverId;
	
	@Autowired
	@Qualifier("game.server.version")
	private String version;
	
	
	@PostConstruct
	void initialize() {
		ThreadGroup threadGroup = new ThreadGroup("user login thread group");
		NamedThreadFactory threadFactory = new NamedThreadFactory(threadGroup, "user login thread");
		executor = new ThreadPoolExecutor(POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(),
				threadFactory);
	}
	
	@Override
	public void putUserLoginQueue(final ChannelHandlerContext context,final Response response,final String channel, final Map<String,String> params) {

		executor.submit(new Runnable() {
			@Override
			public void run() {
				TResult<PlatformLoginResult> result = platformInvoke.login(params);
				if (result.isFail()) {
					UserPushHelper.userLoginFail(context,response, GameStatusCodeConstant.TOKEN_VALIDATE_ERROR);
					return;
				}
				String uid = result.item.uid;
				String reconnectId = playerContext.setLoginData(uid);
				playerContext.setUserLogin(context, channel, uid);
				long actorId = actorService.getActorId(uid);
				UserPushHelper.userLoginSucces(context,response, uid,serverId, actorId, reconnectId);
			}
		});
	}

}
